<template>
  <PageWrapper v-loading="loading" loading-tip="加载中...">
    <div class="p-4 p-4-tag">
      <div class="tag" ref="divDom">
        <div class="main-nav">
          <div class="search-box">
            <a-input-search
              v-model:value="searchDriver"
              placeholder="搜索"
              :allowClear="true"
              @search="onSearchDriver"
            />
          </div>
          <BasicTree
            title=""
            ref="treeRef"
            :treeData="treeDataPro"
            :beforeRightClick="getRightMenuList"
            :actionList="actionList"
            :fieldNames="{ key: 'Key', title: 'Name', children: 'Children' }"
            :onSelect="handleTreeSelect"
          />
        </div>
        <div class="main-content">
          <BasicTable
            @register="registerTable"
            :title="BasicTableTitle"
            :columns="columns"
            :loading="tableLoading"
            :dataSource="tableData"
            :canResize="false"
            :showIndexColumn="false"
            :striped="true"
            :bordered="true"
            :pagination="false"
            :actionColumn="
              hasPermission(['4-1-update', '4-1-code', '4-1-del', '4-1-copy'])
                ? {
                    width: isTemplateCreate ? 100 : 300,
                    title: '操作',
                    dataIndex: 'action',
                    // slots: { customRender: 'action' },
                  }
                : undefined
            "
            rowKey="Name"
            :rowSelection="{
              type: 'checkbox',
              checkStrictly:true,
              onChange(selectedRowKeys){
                onChangeByTable(selectedRowKeys)
              },
              getCheckboxProps(record: Recordable){
                return handleGetCheckProps(record)
              },
              
            }"
          >
            <template #bodyCell="{ column, record }">
              <template v-if="column.key === 'action'">
                <TableAction
                  :actions="[
                    {
                      label: '编辑',
                      icon: 'ant-design:edit-outlined',
                      disabled: +record.TagType === 2,
                      ifShow: !isTemplateCreate && hasPermission('4-1-update'),
                      onClick: (e) => {
                        e.stopPropagation();
                        handleEdit(record);
                      },
                    },
                    {
                      label: '数据转换',
                      icon: 'ant-design:code-outlined',
                      ifShow: hasPermission('4-1-code'),
                      onClick: (e) => {
                        e.stopPropagation();
                        handleCode(record);
                      },
                    },
                    {
                      label: '删除',
                      icon: 'ant-design:delete-outlined',
                      disabled: +record.TagType === 2,
                      ifShow: !isTemplateCreate && hasPermission('4-1-del'),
                      onClick: (e) => {
                        e.stopPropagation();
                        handleDelete(record);
                      },
                    },
                    {
                      label: '复制',
                      icon: 'ant-design:copy-outlined',
                      ifShow: !isTemplateCreate && hasPermission('4-1-copy'),
                      onClick: (e) => {
                        e.stopPropagation();
                        handleCopy(record);
                      },
                    },
                  ]"
                />
              </template>
            </template>

            <template #toolbar>
              <a-input-search
                v-model:value="searchValue"
                placeholder="请输入搜索的变量"
                style="width: 200px"
                :allowClear="true"
                @search="onSearch"
                v-if="isShowSearch"
              />
              <a-button
                type="primary"
                @click="openModalByupload"
                v-if="isShowUpload && !isTemplateCreate && hasPermission('4-1-upload')"
              >
                导入
              </a-button>
              <a-button
                v-if="isShowAdd && !isTemplateCreate && hasPermission('4-1-add')"
                type="primary"
                @click="handleAdd"
              >
                新增
              </a-button>
              <a-button
                v-if="isShowAdd && !isTemplateCreate && hasPermission('4-1-batchAdd')"
                type="primary"
                @click="handleBatchAdd"
              >
                批量新增
              </a-button>
              <a-button
                v-if="isShowBatchDel && !isTemplateCreate && hasPermission('4-1-batchDel')"
                type="primary"
                @click="handleBatchDel"
              >
                批量删除
              </a-button>
              <!-- <a-button type="primary" @click="handleUpdateServer"> 重启服务器 </a-button> -->

              <a-button type="primary" @click="handleSave" v-if="hasPermission('4-1-save')">
                保存到配置文件
              </a-button>
            </template>
          </BasicTable>
          <div class="flex py-2 items-center justify-end pagination-box">
            <a-pagination
              :show-total="(total) => `共 ${total} 条数据`"
              showSizeChanger
              size="small"
              :current="paginationInfo.data.current"
              :pageSize="paginationInfo.data.pageSize"
              :total="paginationInfo.data.total"
              @change="handlePageChange"
            />
          </div>
        </div>
      </div>
      <!-- 设备的表单弹窗 -->
      <modelByDrive
        :formType="formType"
        @register="registerByDrive"
        @submit-success="handelUpdateTree"
      />
      <!-- 分组的表单弹窗 -->
      <modelByGroup
        :formType="formType"
        @register="registerByGroup"
        @submit-success="handelUpdateTree"
      />

      <!-- 表单弹窗 -->
      <modelByDetail
        :info="tagFormInfo"
        :typeOptions="typeOptions"
        :driverregesterOPtions="driverregesterOPtions"
        :addressExtend="addressExtend"
        :readWriteModeOptions="readWriteModeOptions"
        @register="registerByDetail"
        @submit-success="handleUpdateTable"
      />
      <!-- 数据转换弹窗 -->
      <modelByCodemirror @register="registerByCode" @get-code="handleGetCode" :info="tagFormInfo" />

      <!-- 节点弹窗 -->
      <modelByNode
        :formType="formType"
        @register="registerByNode"
        @submit-success="handelUpdateTree"
      />
      <!-- 移动设备弹窗 -->
      <modelByMove
        :formType="formType"
        @register="registerByMove"
        @submit-success="handelUpdateTree"
      />
      <!-- 上传Excel -->
      <uploadExcel
        @register="registerByUpload"
        :classParams="['SuperX.DataService.TagConfig,SuperX.DataService']"
        :uploadParams="{
          ...uploadParams,
          model: 'SuperX.DataService.TagConfig,SuperX.DataService',
          sheetIndex: '-1',
          headRow: '0',
        }"
        @success="handleUploadSuccess"
      />
    </div>
  </PageWrapper>
</template>

<script lang="ts" setup>
  import { PageWrapper } from '/@/components/Page';
  import { BasicTable, TableAction, useTable } from '/@/components/Table';
  import { BasicColumn } from '/@/components/Table/src/types/table';
  import { useModal } from '/@/components/Modal';
  import { cloneDeep } from 'lodash-es';
  import { Pagination } from 'ant-design-vue';

  import modelByDrive from '/@/views/project/tag/components/modelByDrive.vue';
  import modelByGroup from '/@/views/project/tag/components/modelByGroup.vue';
  import uploadExcel from '/@/components/uploadExcel/index.vue';
  import modelByCodemirror from '/@/components/codemirror/index.vue';
  import modelByDetail from '/@/views/project/tag/components/modelByDetail.vue';
  import modelByNode from '/@/views/project/tag/components/modelByNode.vue';
  import modelByMove from '/@/views/project/tag/components/modelByMove.vue';

  import { useMessage } from '/@/hooks/web/useMessage';
  import { reactive, ref, unref, onMounted, nextTick, h, computed } from 'vue';

  import {
    BasicTree,
    TreeActionType,
    TreeActionItem,
    ContextMenuItem,
  } from '/@/components/Tree/index';
  import { usePermission } from '/@/hooks/web/usePermission';
  import { downloadByData, getFileHash } from '/@/utils/file/download';
  import { PlusOutlined } from '@ant-design/icons-vue';

  import {
    GetCopyTagName,
    getDriverTree,
    delDriverInfo,
    delGroupInfo,
    getTagList,
    getDataType,
    delTagInfo,
    deletenode,
    batchDelTag,
    saveConfig,
    addTagInfo,
    downLoadDriver,
    downLoadGroup,
    getReadWriteMode,
    updateTagInfo,
    batchAddTag,
    getdriverregester,
    createtemplate,
    addDriver,
    getDriverInfo,
    updateDriverInfo,
    addGroupInfo,
    updateGroupInfo,
    getGroupInfo,
  } from '/@/api/tag/index';
  import { useI18n } from '/@/hooks/web/useI18n';

  const APagination = Pagination;
  let uploadParams = reactive({
    Parameters: '[]',
    Controller: 'Device',
    Action: 'FileImport',
  });

  let searchDriver = ref('');
  // 分页信息
  let paginationInfo = reactive({
    data: {
      pageSize: 50,
      total: 0,
      current: 1,
    },
  });
  let formType = reactive<any>({
    type: 0, //0是设备，1是分组
    operationType: 0, //0是新增，1是编辑
    id: '', //要编辑的id
    driveId: '', //设备id针对分组的
    nodeName: '', //节点专用
    ParentNodeName: '', //节点专用
    addDriver,
    getDriverInfo,
    updateDriverInfo,
    addGroupInfo,
    updateGroupInfo,
    getGroupInfo,
  });
  let tableParams = reactive({
    driveId: '',
    groupId: '',
  });
  // 是否显示批量删除
  let isShowBatchDel = ref(false);
  let searchValue = ref('');
  let curType = ref(0);
  let tagFormInfo: any = reactive({ data: {}, addTagInfo, updateTagInfo, batchAddTag, type: '' });
  let typeOptions = reactive([]);
  let driverregesterOPtions = reactive([]);
  let readWriteModeOptions = reactive([]);
  const { hasPermission } = usePermission();
  const { createConfirm, createMessage } = useMessage();
  const { t } = useI18n();
  let treeDataPro = ref([]);
  let BasicTableTitle = ref('');
  //  是否模板创建
  let isTemplateCreate = ref(false);
  // 控制变量新增\编辑 表单里面的"关联变量"操作模式 0：地址为输入模式 1：时从列表获取
  let addressExtend = ref(0);
  let loading = ref(false);
  let isSearch = false;
  let tableLoading = ref(false);
  let tableData = reactive([]);
  let treeClickCount = 0;

  // 表格表头
  let columns: BasicColumn[] = [
    {
      title: '变量',
      dataIndex: 'Name',
    },
    {
      title: '地址',
      dataIndex: 'Address',
    },
    {
      width: 77,
      title: '数据类型',
      dataIndex: 'DataTypeCn',
    },
    {
      width: 77,
      title: '读写模式',
      dataIndex: 'ReadWriteModeOptionCn',
    },

    {
      width: 90,
      title: '长度',
      dataIndex: 'Size',
    },
    {
      width: 77,
      title: '是否归档',
      dataIndex: 'ArchiveCn',
    },
    {
      width: 77,
      title: '显示台账',
      dataIndex: 'DisplayCn',
    },
    {
      width: 100,
      title: '最大值',
      dataIndex: 'Maximum',
    },
    {
      width: 100,

      title: '最小值',
      dataIndex: 'Minimum',
    },
    {
      width: 100,
      title: '单位',
      dataIndex: 'Unit',
    },
    {
      title: '变量描述',
      dataIndex: 'Description',
    },
  ];
  const actionList: TreeActionItem[] = [
    {
      show: (node) => {
        return [0].indexOf(node.Type) >= 0 && hasPermission('4-1-addDevice');
      },
      render: (node) => {
        return h(PlusOutlined, {
          class: 'ml-2',
          onClick: (e) => {
            e.stopPropagation();
            handleSetFormType(node, 0);
            if ([0, 3].indexOf(node.Type) >= 0) {
              openModalByDrive(true, {});
            } else {
              openModalByGroup(true, {});
            }
          },
        });
      },
    },
  ];
  const [registerTable, { getSelectRowKeys, clearSelectedRowKeys }] = useTable();
  const [registerByDrive, { openModal: openModalByDrive, closeModal: closeModalByDrive }] =
    useModal();
  const [registerByGroup, { openModal: openModalByGroup, closeModal: closeModalByGroup }] =
    useModal();
  const [registerByUpload, { openModal: openModalByupload, closeModal: closeModalByupload }] =
    useModal();
  const [registerByNode, { openModal: openModalByNode, closeModal: closeModalByNode }] = useModal();
  const [registerByMove, { openModal: openModalByMove, closeModal: closeModalByMove }] = useModal();

  const [registerByDetail, { openModal: openModalByDetail, closeModal: closeModalByDetail }] =
    useModal();
  const [registerByCode, { openModal: openModalByCode, closeModal: closeModalByCode }] = useModal();
  const treeRef = ref<Nullable<TreeActionType>>(null);
  const divDom: any = ref(null);
  const isShowAdd = computed(() => curType.value === 2);
  const isShowUpload = computed(() => curType.value === 2 || curType.value === 1);
  const isShowSearch = computed(() => curType.value === 2 || curType.value === 1);
  onMounted(async () => {
    initData(true);
    typeOptions = await getDataType();
    readWriteModeOptions = await getReadWriteMode();
  });
  // 上传成功
  function handleUploadSuccess() {
    closeModalByupload();
    onSearch();
  }
  // 右键菜单
  function getRightMenuList(node: any): ContextMenuItem[] {
    let targetName = node.Type === 1 ? '设备' : node.Type === 2 ? '分组' : '节点';
    return [
      {
        hidden: !([0, 3, 4].indexOf(node.Type) >= 0 && hasPermission('4-1-addDevice')),
        label: `新增设备`,
        handler: () => {
          // e.stopPropagation();
          handleSetFormType(node, 0);
          // 添加设备
          openModalByDrive(true, {});
        },
        icon: 'ant-design:plus-outlined',
      },
      {
        hidden: !(node.Type === 1 && !node.CreatedByTemplate && hasPermission('4-1-addGroup')),
        label: `新增分组`,
        handler: () => {
          // e.stopPropagation();
          handleSetFormType(node, 0);
          // 添加分组
          openModalByGroup(true, {});
        },
        icon: 'ant-design:plus-outlined',
      },
      {
        hidden: !([0, 3].indexOf(node.Type) >= 0 && hasPermission('4-1-addNode')),
        label: '新增节点',
        handler: () => {
          // e.stopPropagation();
          handleSetFormType(node, 0);
          // 添加节点
          openModalByNode(true, {});
        },
        icon: 'ant-design:folder-add-outlined',
      },
      {
        hidden: !(node.Type === 1 && !node.CreatedByTemplate && hasPermission('4-1-addTemplate')),
        label: '添加模板',
        handler: () => {
          // e.stopPropagation();
          createConfirm({
            iconType: 'warning',
            title: () => h('span', '温馨提示'),
            okText: '确认',
            content: () => h('span', `是否确认在该（${node.title}）设备下添加模板？`),
            onOk: () => {
              createTemplateFn(node);
            },
          });
        },
        icon: 'ant-design:file-add-outlined',
      },
      {
        hidden: !(
          //1=》导出设备  2=>导出分组
          (
            (node.Type === 1 && hasPermission('4-1-exportDevice')) ||
            (node.Type === 2 && hasPermission('4-1-exportGroup'))
          )
        ),
        label: `导出${targetName}`,
        handler: () => {
          handleDownLoad(node);
        },
        icon: 'ant-design:download-outlined',
      },
      {
        hidden: !(
          //3,4=》编辑节点  1=》编辑设备 2&&不是模板 =》 编辑分组
          (
            ([3, 4].indexOf(node.Type) >= 0 && hasPermission('4-1-updateNode')) ||
            ([1].indexOf(node.Type) >= 0 && hasPermission('4-1-updateDevice')) ||
            (!node.CreatedByTemplate && node.Type === 2 && hasPermission('4-1-updateGroup'))
          )
        ),
        label: `编辑${targetName}`,
        handler: () => {
          handleSetFormType(node, 1);
          if ([3, 4].indexOf(node.Type) >= 0) {
            openModalByNode(true, {});
          } else if (node.Type === 1) {
            openModalByDrive(true, {});
          } else if (node.Type === 2) {
            openModalByGroup(true, {});
          }
        },
        icon: 'ant-design:edit-outlined',
      },
      {
        hidden: !([1].indexOf(node.Type) >= 0 && hasPermission('4-1-moveDevice')),
        label: '移动设备',
        handler: () => {
          // e.stopPropagation();
          handleSetFormType(node, 1);
          // 添加节点
          openModalByMove(true, {});
        },
        icon: 'simple-line-icons:cursor-move',
      },
      {
        hidden: !(
          ((node.Type === 1 && hasPermission('4-1-delDevice')) ||
            (node.Type === 2 && hasPermission('4-1-delGroup')) ||
            (node.Type === 3 && hasPermission('4-1-delNode'))) &&
          [0, 1].indexOf(node.SystemType) >= 0
        ),
        label: `删除${targetName}`,
        handler: () => {
          let targetName = '';
          switch (node.Type) {
            case 1:
              targetName = '设备';
              break;
            case 2:
              targetName = '分组';
              break;
            case 3:
              targetName = '节点';
              break;
            default:
              break;
          }
          createConfirm({
            iconType: 'warning',
            title: () => h('span', '温馨提示'),
            okText: '确认',
            content: () => h('span', `是否确认删除该${targetName}（${node.title}）`),
            onOk: async () => {
              try {
                if (node.Type === 1) {
                  await delDriverInfo([node.Key]);
                } else if (node.Type === 2) {
                  await delGroupInfo([node.Parentkey, node.Key]);
                } else {
                  await deletenode([node.title]);
                }

                createMessage.success(t('layout.setting.operatingTitle'));
                initData();
              } catch (error) {}
            },
          });
        },
        icon: 'ant-design:delete-outlined',
      },
    ];
  }
  // 搜索设备
  function onSearchDriver() {
    initData();
  }
  // 搜索方法
  function onSearch() {
    isSearch = ['', null, undefined].indexOf(searchValue.value) === -1;

    paginationInfo.data.current = 1;
    setTagList();
  }
  function handleGetCheckProps(record) {
    return { disabled: +record.TagType === 2 };
  }
  async function handleGetCode(val) {
    try {
      await updateTagInfo([
        tagFormInfo.data.driveId,
        tagFormInfo.data.groupId,
        tagFormInfo.data.Name,
        {
          ...tagFormInfo.data,
          Script: val.code,
          ScaleValue: val.scaleValue,
          ConverterType: +val.converterType,
        },
      ]);

      createMessage.success(t('layout.setting.operatingTitle'));
      tagFormInfo.data = {};
      tagFormInfo.type = '';

      // loading = false;
      closeModalByCode();
      setTimeout(() => {
        // paginationInfo.data.current = 1;
        setTagList();
      }, 250);
    } catch (error) {
      tagFormInfo.data = {};
      tagFormInfo.type = '';

      // loading = false;
      closeModalByCode();
    }
  }
  async function createTemplateFn(v) {
    let res = await createtemplate([v.Key]);
    let dataInfo = res.data;
    if (dataInfo.Code === 0 && dataInfo.Data) {
      createMessage.success(t('layout.setting.operatingTitle'));
    } else {
      createMessage.error(dataInfo.Message);
    }
  }
  // async function handleUpdateServer() {
  //   try {
  //     await updateServer([true]);
  //     createMessage.success(t('layout.setting.operatingTitle'));
  //   } catch (error) {}
  // }
  function handelUpdateTree() {
    closeModalByDrive();
    closeModalByGroup();
    closeModalByMove();
    closeModalByNode();
    initData();
  }
  async function handleDownLoad(val) {
    let title = val.title;
    let key = val.Key;
    let parentTitle = '';
    if (val.Type === 2) parentTitle = val.Parentkey;
    let res =
      val.Type === 1 ? await downLoadDriver([key]) : await downLoadGroup([parentTitle, key]);
    const blob = new Blob([res.data], { type: 'application/octet-stream' });
    let hash = await getFileHash(blob);
    let resHash = res.headers['FileSHA'] || res.headers['filesha'] || '';

    if (hash === resHash) {
      downloadByData(res.data, `${title}.xlsx`);
    } else {
      createMessage.warning('文件数据缺失，请重新下载');
    }
  }

  function getTree() {
    const tree = unref(treeRef);
    if (!tree) {
      throw new Error('tree is null!');
    }
    return tree;
  }
  function eachTree(treeDatas: any[]) {
    treeDatas.forEach((element) => {
      element.title = element.Name;
      switch (element.Type) {
        case 0:
          element.icon = 'ant-design:home-outlined';
          break;
        case 1:
          element.icon = 'ant-design:database-outlined';
          break;
        case 2:
          element.icon = 'ant-design:bars-outlined';
          break;
        case 3:
          element.icon = 'ant-design:folder-outlined';
        case 4:
          element.icon = 'ant-design:folder-outlined';
          break;
        default:
          break;
      }

      if (element.Children) eachTree(element.Children);
    });
  }
  async function initData(isOpenTree = false) {
    loading.value = true;
    let resByTree = await getDriverTree(searchDriver.value ? [searchDriver.value] : [null]);
    eachTree(resByTree);
    treeDataPro.value = resByTree || [];
    if (isOpenTree) {
      nextTick(() => {
        getTree().filterByLevel(1);
      });
    }

    loading.value = false;
  }
  function handleBatchAdd() {
    tagFormInfo.data = tableParams;
    tagFormInfo.type = 'batchAdd';

    openModalByDetail(true, {});
  }
  function handleAdd() {
    tagFormInfo.data = tableParams;
    tagFormInfo.type = 'add';
    openModalByDetail(true, {});
  }
  function handleSave() {
    createConfirm({
      iconType: 'warning',
      title: () => h('span', '温馨提示'),
      okText: '确认',
      content: () => h('span', `此操作将会把页面内容保存到配置文件，是否确认该操作？`),
      onOk: async () => {
        try {
          await saveConfig();
          createMessage.success(t('layout.setting.operatingTitle'));
        } catch (error) {}
      },
    });
  }
  async function handleCopy(record: Recordable) {
    let params = cloneDeep(record);
    params.Name = await GetCopyTagName([tableParams.driveId, tableParams.groupId, params.Name]);
    await addTagInfo([tableParams.driveId, tableParams.groupId, params]);
    createMessage.success(t('layout.setting.operatingTitle'));
    setTagList();
    // createConfirm({
    //   iconType: 'warning',
    //   title: () => h('span', '温馨提示'),
    //   okText: '确认',
    //   content: () => h('span', `是否确认复制该tag（${params.Name}）`),
    //   onOk: async () => {
    //     try {

    //     } catch (error) {}
    //   },
    // });
  }
  function handleBatchDel() {
    let keys = getSelectRowKeys();
    createConfirm({
      iconType: 'warning',
      title: () => h('span', '温馨提示'),
      okText: '确认',
      content: () => h('span', `是否确认删除选择的tag（${keys.join('、')}）`),
      onOk: async () => {
        try {
          await batchDelTag([tableParams.driveId, tableParams.groupId, keys]);

          createMessage.success(t('layout.setting.operatingTitle'));
          setTagList();
        } catch (error) {}
      },
    });
  }
  function handleDelete(record: Recordable) {
    createConfirm({
      iconType: 'warning',
      title: () => h('span', '温馨提示'),
      okText: '确认',
      content: () => h('span', `是否确认删除该tag（${record.Name}）`),
      onOk: async () => {
        try {
          await delTagInfo([tableParams.driveId, tableParams.groupId, record.Name]);
          createMessage.success(t('layout.setting.operatingTitle'));

          setTagList();
        } catch (error) {}
      },
    });
  }
  function handleEdit(record: Recordable) {
    tagFormInfo.data = { ...tableParams, ...record };
    tagFormInfo.type = 'edit';
    openModalByDetail(true, {});
  }
  function handleCode(record: Recordable) {
    tagFormInfo.data = { ...tableParams, ...record };
    tagFormInfo.type = 'code';

    openModalByCode(true, {});
  }
  function handlePageChange(page, pageSize) {
    paginationInfo.data.current = page;
    paginationInfo.data.pageSize = pageSize;
    setTagList();
  }
  function onChangeByTable(selectedRowKeys) {
    isShowBatchDel.value = selectedRowKeys.length > 0;
  }
  function setUploadParams(type, info) {
    uploadParams.Parameters = JSON.stringify([(type === 1 ? info.Key : info.Parentkey) as never]);
  }
  async function handleClickByTree(info) {
    BasicTableTitle.value = info.node?.title || '';
    isTemplateCreate.value = info.node?.CreatedByTemplate || false;
    addressExtend.value = info.node?.AddressExtend || 0;
    searchValue.value = '';
    let { Type, Children = [] } = info.node;
    curType.value = +Type;
    if ((Type === 1 && Children && Children.length > 0) || Type === 2) {
      let targetGroup = Type === 1 ? Children[0] : info.node;
      setUploadParams(Type, info.node);
      BasicTableTitle.value = targetGroup.title;

      isTemplateCreate.value = targetGroup.CreatedByTemplate;
      addressExtend.value = targetGroup.AddressExtend;

      tableParams.groupId = targetGroup.Key;
      tableParams.driveId = targetGroup.Parentkey;
      paginationInfo.data.current = 1;

      setTagList();
      driverregesterOPtions = [];
      let objs = await getdriverregester([targetGroup.Parentkey]);
      for (let key in objs) {
        driverregesterOPtions.push({ value: key, label: key });
      }
    } else {
      BasicTableTitle.value = '';
      isTemplateCreate.value = false;
      addressExtend.value = 0;

      uploadParams.Parameters = '[]';
      tableData = [];
      tableParams.groupId = '-1';
      tableParams.driveId = '-1';
      driverregesterOPtions = [];
    }
  }
  function handleDbClickByTree(info) {
    let val = info.node || {};
    if (!([1, 3, 4].indexOf(val.Type) >= 0 || (!val.CreatedByTemplate && val.Type === 2))) return;
    handleSetFormType(val, 1);
    if ([3, 4].indexOf(val.Type) >= 0) {
      openModalByNode(true, {});
    } else if (val.Type === 1) {
      openModalByDrive(true, {});
    } else if (val.Type === 2) {
      openModalByGroup(true, {});
    }
  }
  function handleTreeSelect(_e, info) {
    treeClickCount++;

    //单次点击次数超过2次不作处理,直接返回,也可以拓展成多击事件
    if (treeClickCount >= 2) {
      return;
    }
    //计时器,计算300毫秒为单位,可自行修改
    setTimeout(() => {
      if (treeClickCount == 1) {
        //把次数归零
        treeClickCount = 0;
        // 单击事件
        handleClickByTree(info);
      } else if (treeClickCount > 1) {
        //把次数归零
        treeClickCount = 0;
        //双击事件
        handleDbClickByTree(info);
      }
    }, 300);
  }
  function handleUpdateTable() {
    closeModalByDetail();
    setTimeout(() => {
      // paginationInfo.data.current = 1;
      setTagList();
    }, 250);
  }
  async function setTagList() {
    clearSelectedRowKeys();
    try {
      tableLoading.value = true;
      let res = await getTagList([
        {
          DriverKey: tableParams.driveId,
          GroupKey: tableParams.groupId,
          PageNO: paginationInfo.data.current,
          SearchValue: isSearch ? searchValue.value : '',
          PageSize: paginationInfo.data.pageSize,
        },
      ]);
      paginationInfo.data.total = res.TotalRows;
      tableData = res.Rows.map((item) => {
        item.ArchiveCn = item.Archive ? '是' : '否';
        item.DisplayCn = item.Display ? '是' : '否';
        let targetTypes = typeOptions.filter((v) => v.Value === item.DataType);
        item.DataTypeCn = targetTypes.length > 0 ? targetTypes[0].Key : '';
        let targetReadWriteModes = readWriteModeOptions.filter(
          (v) => v.Value === item.ReadWriteMode,
        );
        item.ReadWriteModeOptionCn =
          targetReadWriteModes.length > 0 ? targetReadWriteModes[0].Key : '';

        return item;
      });
      tableLoading.value = false;
    } catch (error) {
      tableLoading.value = false;
    }
  }
  function handleSetFormType(v, operationType) {
    let { Type, Key, Parentkey, title } = v;
    formType.operationType = operationType;
    formType.nodeName = [3, 4].indexOf(Type) >= 0 ? title : null;
    formType.ParentNodeName =
      Type === 3 && operationType === 0 ? title : Type === 4 ? Parentkey : null;
    formType.type =
      [0, 3].indexOf(Type) >= 0 || ([1].indexOf(Type) >= 0 && operationType === 1) ? 0 : 1;
    formType.id = operationType === 1 ? Key : '';
    formType.driveId = operationType === 1 ? Parentkey : Key;
  }
</script>
<script lang="ts">
  export default {
    name: 'TagIndexPage',
  };
</script>
<style scoped lang="less">
  .p-4-tag {
    width: 100%;
    height: 100%;
    padding: 0px !important;
  }

  .tag {
    position: relative;
    overflow: hidden;
    height: 100%;
    background-color: #fff;

    .main-nav {
      position: absolute;
      top: 0;
      left: 0;
      bottom: 0;
      width: 240px;
      height: 100%;
      padding: 8px;
      box-sizing: border-box;
      overflow: auto;
      background-color: rgba(8, 30, 66, 0.04);
      border-radius: 3px;

      ::v-deep(.vben-tree__title) {
        user-select: none !important;
      }
    }

    .main-content {
      position: relative;
      height: 100%;
      margin-left: 260px;
      overflow: hidden;

      .pagination-box {
        z-index: 9;
        padding: 10px 5px;
        box-sizing: border-box;
        position: absolute;
        width: 100%;
        bottom: 0;
        left: 0;
        right: 0;
        background-color: #fff;
      }
    }

    .main-content::after {
      content: '';
      display: block;
      width: 100%;
      height: 45px;
    }
  }
</style>
